package org.sanguine.study.hometasks.first.task.a;

import java.util.Arrays;
import java.util.regex.Pattern;

import org.sanguine.study.hometasks.first.Runner;

public class TaskA8 extends CommonWordTask {
	private String firstPalindromeNumber;
	private String secondPalindromeNumber;

	public static void main(String[] args) {
		Runner runner = new TaskA8();
		runner.run(args);
	}

	
	
	@Override
	protected void readItems() {
		super.readItems();
		
		if (items == null) return;
		
		String[] numberItems = new String[items.length];
		
		int j = 0;
		for (int i = 0; i < items.length; i++) { 
			if (isOnlyDigitWord(items[i])) {
				numberItems[j++] = items[i];
			}
		}
		if (j < items.length) {
			items = Arrays.copyOf(numberItems, j);
		}
	}

	private boolean isOnlyDigitWord(String word) {
		return Pattern.matches("^[0-9]+$", word);
	}

	@Override
	public void doTask() {
		if (in == null || out == null || numberOfItems <= 0) return;
		readItems();
		if (items != null) findSecondPalindrome();
		printResult();
	}

	private void findSecondPalindrome() {
		for (String s : items) {
			if (isPalindrome(s)) {
				if (firstPalindromeNumber == null) firstPalindromeNumber = s;
				else {
					secondPalindromeNumber = s;
					break;
				}
			}
		}
		
	}

	private boolean isPalindrome(String word) {
		char[] chars = word.toLowerCase().toCharArray();
		boolean result = false;
		
		for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
			if (chars[i] != chars[j]) {
				result = false;
				break;
			}
			else result = true;
		}
		return result;
	}

	private void printResult() {
		if (secondPalindromeNumber == null) out.println("Second palindrome number not found");
		else out.printf("Second palindrome number: %s\n", secondPalindromeNumber);
	}

}
